package com.manong.utils;

import com.manong.entity.Permission;
import com.manong.vo.RouterVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 菜单树工具类
 */
public class MenuTree {
    /**
     * 构建路由
     * @param permissionList
     * @param pid
     * @return
     */
    public static List<RouterVo> makeRouter(List<Permission> permissionList,Long pid) {
        List<RouterVo> routerVos = new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<Permission>())
                .stream().filter(item->item!=null && item.getParentId() == pid )
                .forEach( item->{
                    RouterVo router = new RouterVo();
                    router.setName(item.getName());
                    router.setPath(item.getPath());
                    if(item.getParentId()==0L){
                        router.setComponent("Layout");//一级菜单组件
                        router.setAlwaysShow(true);//显示路由
                    }else {
                        router.setComponent(item.getUrl());//具体的组件
                        router.setAlwaysShow(false);//折叠路由
                    }
                    router.setMeta(router.new Meta(item.getLabel(),
                            item.getIcon(),
                            item.getCode().split(",")));
                    //递归生成路由
                    List<RouterVo> children = makeRouter(permissionList, item.getId());
                    router.setChildren(children);//设置子路由到路由对象中
                    //将路由信息添加到集合中
                    routerVos.add(router);
                });
        return routerVos;
    }

    /**
     * 生成菜单树
     * @param meuList
     * @param pid
     * @return
     */
    public static List<Permission> makeMenuTree(List<Permission> meuList, Long pid){
        List<Permission> permissionList = new ArrayList<>();
        Optional.ofNullable(meuList).orElse(new ArrayList<Permission>())
                .stream().filter(item->item!=null && Objects.equals(item.getParentId(), pid))
                .forEach(item->{
                    Permission permission = new Permission();
                    BeanUtils.copyProperties(item,permission);
                    List<Permission> children = makeMenuTree(meuList, item.getId());
                    permission.setChildren(children);
                    permissionList.add(permission);
                });
        return permissionList;
    }
}
